import 'dart:typed_data';

import 'package:tool/rive/buffer_reader_ext.dart';

class RiveHeader {
  final Uint8List bytes;

  RiveHeader(this.bytes);

  late String magic;

  String majorVersion = '';
  String minorVersion = '';

  String get version => '$majorVersion.$minorVersion';

  int fileId = 0;

  final propertyMap = <int, int>{};

  int init() {
    var pos = 0;
    magic = String.fromCharCodes(bytes.sublist(0, 4));
    if (magic != 'RIVE') {
      throw Exception('not a rive file');
    }
    pos += 4;

    final major = bytes.readUleb128(pos);
    majorVersion = major.value.toString();
    pos += major.length;

    final minor = bytes.readUleb128(pos);
    minorVersion = minor.value.toString();
    pos += minor.length;

    final file = bytes.readUleb128(pos);
    fileId = file.value;
    pos += file.length;

    // read property map
    final keys = <int>[];
    while (true) {
      final keyUleb = bytes.readUleb128(pos);
      pos += keyUleb.length;
      if (keyUleb.value == 0) {
        break;
      }
      keys.add(keyUleb.value);
    }

    // read property value
    int currentValue = bytes.readUint32(pos);
    pos += 4;
    int valueBit = 0;
    for (final key in keys) {
      final v = (currentValue >> valueBit) & 3;
      propertyMap[key] = v;
      valueBit += 2;
    }

    return pos;
  }

  String debugString() {
    final propertyMapString = propertyMap.entries
        .map((e) => '   ${e.key} -> ${e.value}')
        .toList()
        .join('\n');
    return 'magic: $magic\nversion: $version\nfileId: $fileId\npropertyMap:\n$propertyMapString';
  }
}
